package com.marry.webservice.interceptor;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.NodeList;

import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;


/**
 * @author ml
 * @create 2017-09-20--14:17
 */
public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    private static final Logger logger= LoggerFactory.getLogger(AuthInterceptor.class);

    private static final String USER_NAME="admin";
    private static final String USER_PASSWORD="pass";
    public AuthInterceptor(){
        super(Phase.PRE_PROTOCOL);
        getAfter().add(SAAJInInterceptor.class.getName());
    }


    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {

        SAAJInInterceptor saa=new SAAJInInterceptor();
        SOAPMessage mess=soapMessage.getContent(SOAPMessage.class);
        if(mess==null){
            saa.handleMessage(soapMessage);
            mess=soapMessage.getContent(SOAPMessage.class);

        }
        SOAPHeader header=null;

        try {
            header=mess.getSOAPHeader();

        } catch (SOAPException e) {
            e.printStackTrace();
        }

        if(header==null){
            throw new Fault(new IllegalArgumentException("找不到Header"));
        }

        NodeList users=header.getElementsByTagName("username");
        NodeList passwords=header.getElementsByTagName("password");

        if(users.getLength()<1){
            throw new Fault(new IllegalArgumentException("找不到用户信息"));
        }
        if(passwords.getLength()<1){
            throw new Fault(new IllegalArgumentException("找不到密码"));
        }

        String userName=users.item(0).getTextContent().trim();
        String password=passwords.item(0).getTextContent().trim();
        if(USER_NAME.equals(userName) && USER_PASSWORD.equals(password)){
            logger.info("admin auth success");
        }else{
            SOAPException exception=new SOAPException("认证失败");
            throw new Fault(exception);

        }



    }
}
